#include "../include/strutil.h"
#include <iterator>

using namespace std;

namespace utility
{
namespace strutil
{
// ----------------------------------------------------------------------
// SplitStringUsing()
//    Split a string using a character delimiter. Append the components
//    to 'result'.
//
// Note: For multi-character delimiters, this routine will split on *ANY* of
// the characters in the string, not the entire string as a single delimiter.
// ----------------------------------------------------------------------
template <typename ITR>
static inline
    void SplitStringToIteratorUsing(const string& full, const char* delim, ITR& result) 
{
    // Optimize the common case where delim is a single character.
    if (delim[0] != '\0' && delim[1] == '\0') {
        char c = delim[0];
        const char* p = full.data();
        const char* end = p + full.size();
        while (p != end) {
            if (*p == c) {
                ++p;
            } else {
                const char* start = p;
                while (++p != end && *p != c);
                *result++ = string(start, p - start);
            }
        }
        return;
    }

    string::size_type begin_index, end_index;
    begin_index = full.find_first_not_of(delim);
    while (begin_index != string::npos) {
        end_index = full.find_first_of(delim, begin_index);
        if (end_index == string::npos) {
            *result++ = full.substr(begin_index);
            return;
        }
        *result++ = full.substr(begin_index, (end_index - begin_index));
        begin_index = full.find_first_not_of(delim, end_index);
    }
}

void SplitStringUsing(const string& full, const char* delim, vector<string>* result) 
{
    back_insert_iterator< vector<string> > it(*result);
    SplitStringToIteratorUsing(full, delim, it);
}

void str_to_lwr(std::string& s)
{
    std::string::iterator it;
    for (it = s.begin(); it != s.end(); ++it) {
        *it = tolower(*it);
    }
}

} // namespace stutil
} // namespace utility
